package com.oliet.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.oliet.common.vo.role.RoleVO;
import com.oliet.entity.Roles;
import com.oliet.entity.UserRoles;
import com.oliet.entity.base.BaseEntity;
import com.oliet.mapper.UserRolesMapper;
import com.oliet.service.RolesService;
import com.oliet.service.UserRolesService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author JZP
 * @since 2023-12-09
 */
@Service
public class UserRolesServiceImpl extends ServiceImpl<UserRolesMapper, UserRoles> implements UserRolesService {

    @Autowired
    private RolesService rolesService;

    @Override
    public void deleteByUserId(Long userId) {
        this.remove(new LambdaQueryWrapper<UserRoles>().eq(UserRoles::getUserId, userId));
    }

    @Override
    public void batchInsert(Long userId, List<Long> roleIds) {
        List<UserRoles> userRolesList = Lists.newArrayList();
        for (Long roleId : roleIds) {
            UserRoles userRoles = new UserRoles();
            userRoles.setUserId(userId);
            userRoles.setRoleId(roleId);
            userRolesList.add(userRoles);
        }
        this.saveBatch(userRolesList);
    }

    @Override
    public List<RoleVO> getRoleVoByUserId(Long userId) {
        List<RoleVO> result = Lists.newArrayList();
        List<UserRoles> userRolesList = this.list(new LambdaQueryWrapper<UserRoles>().eq(UserRoles::getUserId, userId));
        if(CollectionUtil.isEmpty(userRolesList)){
            return result;
        }
        List<Long> roleIds = userRolesList.stream().map(it -> it.getRoleId()).distinct().collect(Collectors.toList());
        List<Roles> roleList = this.rolesService.list(new LambdaQueryWrapper<Roles>().in(BaseEntity::getId, roleIds));
        return RoleVO.poListConverVoList(roleList, Maps.newHashMap());
    }
}
